import axios from 'axios';
import ENV from '@/utils/env';
import { message } from 'antd';
import { showAuthModal } from '../components/AuthModal';
import { saveRedirectPath, AUTH_STORAGE_KEYS } from '../config/authConfig';
import { formCache } from './formCache';
import { handleMockRequest } from './requestMock';
import '../mocks';

let baseURL;
switch (ENV.env) {
  case 'dev':
    baseURL = 'http://39.104.18.179:9001/api';
    break;
  case 'beta':
    baseURL = '/';
    break;
  case 'prod':
    baseURL = import.meta.env.VITE_API_BASE_URL.replace(/:\d+$/, ':9001') + '/api';
    break;
  default:
    baseURL = import.meta.env.VITE_API_BASE_URL.replace(/:\d+$/, ':9001') + '/api';
    break;
}

const request = axios.create({
  baseURL
});

request.getUrl = (path) => {
  let prefix = baseURL;
  if (prefix.indexOf('http') !== 0) {
    prefix = location.origin + prefix;
  }
  return prefix + path;
};

let token = '';
request.setToken = (t) => {
  token = t;
  request.defaults.headers.common['token'] = token;
};

// 从localStorage获取token并设置
const initToken = () => {
  const storedToken = localStorage.getItem('token');
  if (storedToken) {
    request.setToken(storedToken);
  }
};

// 监听localStorage变化
const handleStorageChange = (e) => {
  if (e.key === 'token') {
    if (e.newValue) {
      request.setToken(e.newValue);
    } else {
      request.setToken('');
    }
  }
};

// 初始化token
initToken();

request.initToken = initToken;

// 添加storage事件监听
window.addEventListener('storage', handleStorageChange);

// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    // 检查mock处理（如果匹配会直接throw）
    handleMockRequest(config);
    return config;
  },
  function (error) {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

const errorSilent = true;

// 定义一个变量来防止重复弹出认证Modal
let isShowingAuthModal = false;

request.interceptors.response.use(
  (response) => {
    const config = response.config;
    // 检查响应中的自定义状态码
    if (response.data?.code === 401) {
      // 清除过期的认证信息
      localStorage.removeItem(AUTH_STORAGE_KEYS.TOKEN);
      localStorage.removeItem(AUTH_STORAGE_KEYS.USER);
      
      // 如果配置了表单数据缓存键，保存表单数据
      if (config.formCacheKey && config.data) {
        formCache.save(config.formCacheKey, config.data);
      }
      
      // 避免重复显示
      if (!isShowingAuthModal) {
        isShowingAuthModal = true;
        
        // 保存当前路径
        saveRedirectPath(window.location.pathname + window.location.search);
        
        // 显示认证提示Modal
        showAuthModal({
          isSessionExpired: true,
          onLogin: () => {
            window.location.href = '/#/login';
          },
          onClose: () => {
            isShowingAuthModal = false;
            // 跳转到首页
            window.location.href = '/#/';
          }
        });
      }
      
      return Promise.reject(new Error('Session expired'));
    }
    if (response.data && response.data && response.data.code !== 200) {
      const errMsg = response.data.msg || '请求异常';
      const lines = (
        <div style={{ display: 'inline-block', textAlign: 'left' }}>
          {errMsg.split('\n').map((line, index) => (
            <div key={index}>{line}</div>
          ))}
        </div>
      );
      if (!config.errorSilent && !errorSilent) {
        message.error({
          content: lines,
          duration: 2
        });
      }
      return Promise.reject(new Error(errMsg));
    } else if (!response.data) {
      const errMsg = '请求异常';
      if (!config.errorSilent || !errorSilent) {
        message.error(errMsg);
      }
      return Promise.reject(new Error('请求异常'));
    }

    return response;
  },
  (error) => {
    // 处理mock数据
    if (error.message === 'MOCK_RESPONSE' && error.mockData) {
      return Promise.resolve(error.mockData);
    }
    
    console.log(error);
    if (!errorSilent) {
      message.error(error.message || '请求异常');
    }
    if (error && error.response && error.response.status === 401) {
      // 清除过期的认证信息
      localStorage.removeItem(AUTH_STORAGE_KEYS.TOKEN);
      localStorage.removeItem(AUTH_STORAGE_KEYS.USER);
      
      // 如果配置了表单数据缓存键，保存表单数据
      const config = error.config;
      if (config && config.formCacheKey && config.data) {
        formCache.save(config.formCacheKey, config.data);
      }
      
      // 避免重复显示
      if (!isShowingAuthModal) {
        isShowingAuthModal = true;
        
        // 保存当前路径
        saveRedirectPath(window.location.pathname + window.location.search);
        
        // 显示认证提示Modal
        showAuthModal({
          isSessionExpired: true,
          onLogin: () => {
            window.location.href = '/#/login';
          },
          onClose: () => {
            isShowingAuthModal = false;
            // 跳转到首页
            window.location.href = '/#/';
          }
        });
      }
    }
    return Promise.reject(error);
  }
);

export default request;